<template>
  <div class="branchBaseData" v-loading="loading" element-loading-text="加载中。。。">
    <el-card>
      <el-row>
        <el-col :span="24">
            <el-form :model="searchInfo" size="mini" label-position="top" ref="form">
              <el-row :gutter="10">
                <el-col :lg="5" :md="6">
                  <el-form-item label="机构">
                    <select-tree :tree-data="treedata" :branch="searchInfo.branchName" @getBranchName="getBranch"></select-tree>
                  </el-form-item>
                </el-col>
                <el-col :lg="5" :md="6">
                  <el-form-item label="排班计划编号" prop="SPID">
                    <el-input v-model.trim="searchInfo.SPID" placeholder="请输入排班计划编号"></el-input>
                  </el-form-item>
                </el-col> 
                <el-col :lg="5" :md="6">
                  <el-form-item label="排班计划名称" prop="SPNAME">
                    <el-input v-model.trim="searchInfo.SPNAME" placeholder="请输入排班计划名称"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :lg="5" :md="6">
                  <el-form-item label="开始日期" prop="SRTDATE">
                    <el-date-picker
                      v-model.trim="searchInfo.SRTDATE"
                      value-format="yyyyMMdd"
                      type="date"
                      placeholder="选择日期">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="10" style="margin-bottom: 20px;">
                <el-col>
                  <el-button type="primary" icon='el-icon-search' @click="queryPlanMaintain()" :loading="loading" size='mini'>查询
                  </el-button>
                  <el-button type='warning' size='mini' icon='el-icon-refresh' @click="resetForm('form')">重置</el-button>
                  <el-button type="primary" size="mini" icon='el-icon-plus' @click="update('add')">新增排班计划</el-button>
                </el-col>
              </el-row>
            </el-form>
            <el-table :data="tableData" :span-method="objectSpanMethod" border>
              <el-table-column prop="SPID" label="排班计划编号" width="110" align="center"></el-table-column>
              <el-table-column prop="SPNAME" label="排班计划名称" width="110" align="center"></el-table-column>
              <el-table-column prop="NOTES" label="说明" align="center"></el-table-column>
              <el-table-column prop="BRANCHNO" label="机构号" align="center"></el-table-column>
              <el-table-column prop="BRANCHNAME" label="机构名称" align="center"></el-table-column>
              <el-table-column prop="PERIODTYPE" label="周期方式" :formatter="PERIODTYPEFormat" align="center"></el-table-column>
              <el-table-column prop="PERIODNUM" label="周数/月数" width="90" align="center"></el-table-column>
              <el-table-column prop="SRTDATE" label="开始日期" width="90" align="center"></el-table-column>
              <el-table-column prop="FTEID" label="人力需求编号" width="110" align="center"></el-table-column>
              <el-table-column prop="FTENAME" label="人力需求名称" width="110" align="center"></el-table-column>
              <el-table-column prop="SKILLFLG" label="技能" width="110" align="center"></el-table-column>
              <el-table-column label="操作"  fixed="right" width="80" align="center">
                <template slot-scope="scope" >
                  <el-tooltip class="item" effect="dark" content="修改" placement="top">
                    <el-button type="text" style="margin-left:0px" @click="update('edit',scope.row)">
                      <i class="el-icon-edit-outline"></i>
                    </el-button>
                  </el-tooltip>
                  <el-tooltip class="item" effect="dark" content="删除" placement="top">
                    <el-button type="text" style="margin-left:0px" @click="delClick(scope.row)">
                      <i class="el-icon-delete"></i>
                    </el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-pagination style="text-align: right; margin-top:20px;" 
            :page-sizes="[10, 20, 50, 100]" 
            :page-size="pageSize" 
            @size-change="handleInSizeChange" 
            @current-change="handleInCurrentChange" 
            :current-page="currpage" 
            background layout="sizes, total, prev, pager, next, jumper" 
            :total="tableTotal">
          </el-pagination>
        </el-col>
      </el-row>
      <component :is="dialogList.editDialog" :option="editOptions" ref="myChild"></component>
    </el-card>
  </div>
</template>

<script>
  import request from "@/common/utils/requestWFM";
  import getGlobalParams from "@/common/utils/getGlobalParams";
  import queryPlanMaintain from '@/message/wfm/intelligenceSchedule/planMaintain/queryPlanMaintain'
  import delPlanMaintain from '@/message/wfm/intelligenceSchedule/planMaintain/delPlanMaintain'
  import editDialog from './dialog/editDialog';
  import selectTree from "@/components/selectTree5/"
    import dataQuery from '@/message/wfm/baseData/dictionaryManage/dictionaryQuery'
  import FQuery from '@/message/wfm/intelligenceSchedule/FTEMaintain/FTEQuery'

  export default {
    components: {
      selectTree
    },
    data() {
      return {
        FTEOption:[],//人力需求
        skillOption:[],//坐席技能
        tableTotal: 1,
        currpage: 1,
        pageSize: getGlobalParams.get("PageSize"),
        editOptions:{
          isShow:false,
          title: '',
        },
        dialogList: { editDialog },
        defaultProps: {
          children: 'children',
          label: 'BRANCHNAME'
        },
        resData: "",
        treedata: [],
        loading: false,
        periodtypes: [{
          value: 'week',
          label: '周'
        },{
          value: 'month',
          label: '月'
        },],
        tableData: [],
        searchInfo: {
          SPNAME: '',
          SRTDATE: '',
          SPID: '',
          branchName: this.$store.getters.BranchName,
          BRANCHNO: [],
          branchNO:this.$store.getters.BranchNum,
        },
        checkedIds: [], //机构下拉框V-model数据
        spanArr: [],
      }
    },
    computed: {
      
    },
    watch: {
    },
    mounted() {
      this.queryPlanMaintain();
      this.skillDataQuery()
      this.FTEQuery()
    },
    methods: {
      // 人力需求查询
      async FTEQuery() {
        let resBody = new FQuery()
        resBody.data.BRANCHNO = this.searchInfo.branchNO
        let response = await request(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
          this.FTEOption = response.BODY.RSPSTRUCT;
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          })
        }
      },
       // 查询坐席技能数据字典
      async skillDataQuery() {
        let resBody = new dataQuery();
        resBody.data.FIELDCODE = 'AGENTSKILL'
        resBody.data.CurrPage = '1'
        resBody.data.PageRowNum = '100'
        let response = await request(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
          this.skillOption = response.BODY.FIEDATA;
          // if(this.skillOption.length>0){
          //   this.skillOption.forEach(item=>{
          //     item.SKILLLEVEL = 0.1
          //   })
          // }
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          })
        }
      },
      getBranch(data){
        this.searchInfo.branchNO = data.BRANCHNO
        this.searchInfo.branchName= data.BRANCHNAME
        this.FTEQuery()
      },
      //前端分页
      handleInCurrentChange(val) {
        this.currpage = val;
        this.queryPlanMaintain();
      },
      handleInSizeChange(val) {
        this.pageSize = val;
        this.queryPlanMaintain();
      },
      findName(arr,val) {
        let data = arr.filter(item => {
          return item.skill == val
        })
        if (data.length)
          return data
      },
      update(edit,row) {
        let outArr = []
        let insideArr = []
        if(this.FTEOption==undefined||this.FTEOption.length==0){
          this.$message.error('该机构下没有人力需求，请先配置人力需求')
          return false
        }
        this.FTEOption.forEach(item => {
          insideArr.push({
            value: item.FTEID,
            label: item.FTENAME,
            skill:item.SKILLFLG
          })
        })
        this.skillOption.forEach(item => {
          outArr.push({
            value: item.FIELDKEY,
            label: item.FIELDVALUE,
            children: this.findName(insideArr,item.FIELDKEY)
          })
        })
        this.editOptions.options = outArr
        this.editOptions.operation = edit;
        this.editOptions.skillOption = this.skillOption;
        if(edit == 'add'){
          this.editOptions.isShow = true;
          this.editOptions.title = '新增排班计划';
        }else if(edit == 'edit'){
          // let FTESKill= []
          // this.tableData.forEach(item=>{
          //   if(item.SPID == row.SPID){
          //     FTESKill.push([
          //       item.SKILLFLG,item.FTEID
          //     ])
          //   }
          // })
          this.editOptions.isShow = true;
          this.editOptions.title = '修改排班计划';
          this.editOptions.row = row;
          this.editOptions.tableData =this.tableData;
        }
      },
      PERIODTYPEFormat(row, column){
        return row.PERIODTYPE == 'month'?'月':row.PERIODTYPE == 'week'?'周':'';
      },
      handleNodeClick(data) {
        // console.log(data);
      },
      // 保存
      submitForm(formName,operation) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.editBranchData();
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      // 查询
      async queryPlanMaintain(SPID) {
        this.loading = true;
        let resBody = new queryPlanMaintain();
        resBody.data.BRANCHNO = this.searchInfo.branchNO;
        resBody.data.SPNAME = this.searchInfo.SPNAME;
        resBody.data.SRTDATE = this.searchInfo.SRTDATE;
        resBody.data.SPID = SPID?SPID:this.searchInfo.SPID;
        resBody.data.CurrPage = this.currpage; 
        resBody.data.PageRowNum = SPID?'100':this.pageSize;
        let response = await request(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
          // 查询出数据
          if(SPID){
            this.$refs.myChild.getData(response.BODY.RSPSTRUCT);
          }else{
            this.tableData = response.BODY.RSPSTRUCT;
            this.tableData.map(function(value){
              value.BRANCHNAME = response.BODY.BRANCHNAME;
            })
            this.tableTotal = response.BODY.TotalRowNum;

            this.spanArr = [];
            let contactDot = 0;
            this.tableData.forEach((info, index) => {
              if (index - 1 >= 0 && info.SPID === this.tableData[index - 1].SPID) {
                this.spanArr[contactDot] += 1;
                this.spanArr.push(0);
              } else {
                contactDot = index;
                this.spanArr.push(1);
              }
            });
          }
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          });
        }
        this.loading = false;
      },
      // 删除
      async delPlanMaintain(row) {
        this.loading = true;
        let resBody = new delPlanMaintain();
        resBody.data.SPID = row.SPID;
        let response = await request(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
          this.$message({
            type: "success",
            message: "删除成功"
          });
          this.queryPlanMaintain();
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          });
        }
        this.loading = false;
      },
      // 时间切割成开始,结束格式
      timeSplit(time){
        var str = '';
        var obj = {};
        if(time){
          str = time.split('-');
          obj = {"start":str[0],"end":str[1]};
        }else{
          obj = {"start":"00:00","end":'00:00'};
        }
        return obj;
      },
      // 删除分配规则
      delClick(row){
        this.$confirm("是否确定删除记录，删除操作无法恢复！", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
          .then(() => {
            this.delPlanMaintain(row);
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          });
      },
      // 单元格合并
      objectSpanMethod({ row, column, rowIndex, columnIndex }) {
        if (columnIndex !== 8 && columnIndex !== 9 && columnIndex !== 10) {
          if (this.spanArr[rowIndex]) {
            return {
              rowspan: this.spanArr[rowIndex],
              colspan: 1
            }
          } else {
            return {
              rowspan: 0,
              colspan: 0
            }
          }
        }
      },
    }
  };

</script>

<style lang="scss" scoped>

</style>
